package com.sl.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.itheima.auth.factory.AuthTemplateFactory;
import com.itheima.auth.sdk.AuthTemplate;
import com.itheima.auth.sdk.dto.AuthUserInfoDTO;
import com.itheima.auth.sdk.service.TokenCheckService;
import com.sl.gateway.config.MyConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

/**
 * @author 姜星宇
 * @date 2024/9/3 18:01
 */
@Component
public class ManagerTokenGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> implements AuthFilter {
//        private static  final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
//        private TokenCheckService tokenCheckService;
//        @Resource
//        private MyConfig myConfig;
//
//        @Value("${role.manager}")
//        private List<Long> managerRoleList;
//
//        @Override
//        public GatewayFilter apply(Object config) {
//            return (exchange,chain)->{
//                ServerHttpRequest request = exchange.getRequest();
//                ServerHttpResponse response = exchange.getResponse();
//
//
//                //1.校验请求是否在白名单中，如果在，直接放行
//                String path = request.getPath().toString();
//               for (String noAuthPath : this.myConfig.getNoAuthPaths()) {
//                    if(ANT_PATH_MATCHER.match(noAuthPath,path)){
//                        //白名单放行
//                        return chain.filter(exchange);
//
//                    }
//             }
//                if (StrUtil.startWithAny(path, this.myConfig.getNoAuthPaths())) {
//                    //直接放行
//                    return chain.filter(exchange);
//                }
//                //2.获取请求头中的token,对token的有效性进行校验
//                String token = request.getHeaders().getFirst(Constants.GATEWAY.AUTHORIZATION);
//                if(StrUtil.isEmpty(token)){
//                    //非法请求,响应401
//                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                    return response.setComplete();
//                }
//
//                //3.校验token的有效性
//                AuthUserInfoDTO authUserInfoDTO = null;
//                try {
//                   authUserInfoDTO = this.tokenCheckService.parserToken(token);
//                } catch (Exception e) {
//                  //  throw new RuntimeException(e);
//                    // 出现异常是正确的
//                }
//                if(ObjectUtil.isEmpty(authUserInfoDTO)){
//                    //token失效
//                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                    return response.setComplete();
//                }
//                //4.校验权限，校验是否为管理员，如果不是进行拦截，通过用户的角色进行校验
//                //思路：先查询到当前用户的角色列表，判断是否有允许访问的角色，如果有就放行
//                AuthTemplate authTemplate = AuthTemplateFactory.get(token);
//                List<Long> roleIds = authTemplate.opsForRole().findRoleByUserId(authUserInfoDTO.getUserId()).getData();
//                Collection<Long> intersection = CollUtil.intersection(roleIds,this.managerRoleList);
//                if(CollUtil.isEmpty(intersection)) {
//                    //没有权限访问，响应400
//                    response.setStatusCode(HttpStatus.BAD_REQUEST);
//                    return response.setComplete();
//                }
//                //放行
//                request.mutate().header(Constants.GATEWAY.USERINFO, JSONUtil.toJsonStr(authUserInfoDTO));
//                request.mutate().header(Constants.GATEWAY.TOKEN, token);
//                return chain.filter(exchange);
//            };
//        }

    @Resource
    private MyConfig myConfig;

    @Resource
    private TokenCheckService tokenCheckService;

    @Value("${role.manager}")
    private List<Long> managerRoleList;
    @Override
    public GatewayFilter apply(Object config) {
            return new TokenGatewayFilter(this,myConfig);

    }

    @Override
    public AuthUserInfoDTO check(String token) {
        return this.tokenCheckService.parserToken(token);
    }

    @Override
    public Boolean auth(String token, AuthUserInfoDTO authUserInfo, String path) {
        //校验权限，如果是非管理员不能登录
        AuthTemplate authTemplate = AuthTemplateFactory.get(token);
        //获取用户拥有的角色id列表
        List<Long> roleIds = authTemplate.opsForRole().findRoleByUserId(authUserInfo.getUserId()).getData();
        //取交集，判断用户拥有的角色是否与预定的角色列表是否有交集
        Collection<Long> intersection = CollUtil.intersection(roleIds, this.managerRoleList);
        return CollUtil.isNotEmpty(intersection);
    }
}
